import * as THREE from "three";
import { getImageSize } from "@/utils/imageUtils";
import data from "./floor";

const baseUrl = "http://47.113.185.182:7374";
let imgInfo = {};

export default async (floorInfo) => {
  const floorGroup = new THREE.Group();

  //创建楼层拓扑图
  await createTopo(floorGroup, floorInfo.mapUrl);
  //创建房间/AP标记
  createRoomMark(floorGroup);

  floorGroup.scale.set(0.01, 0.01, 0.01);
  return floorGroup;
};

//创建楼层拓扑图
const createTopo = async (floorGroup, url) => {
  imgInfo = await getImageSize(url, "楼层图");
  let floorTexture = new THREE.TextureLoader().load(baseUrl + url);

  //创建楼层平面
  const floor = new THREE.Mesh(
    new THREE.PlaneGeometry(imgInfo.width, imgInfo.height),
    new THREE.MeshBasicMaterial({
      map: floorTexture,
      transparent: true, // 启用透明
      alphaTest: 0.5
    })
  );
  floor.rotation.x = -Math.PI / 2;
  floor.name = "floor_base";
  floorGroup.add(floor);

  //创建白色背景平面
  const floorBack = new THREE.Mesh(
    new THREE.PlaneGeometry(imgInfo.width * 1.01, imgInfo.height * 1.01),
    new THREE.MeshBasicMaterial({
      color: "#fff"
    })
  );
  floorBack.rotation.x = -Math.PI / 2;
  floorBack.position.y = -0.1; // 放在原始平面后方一点
  floorBack.name = "floor_base";
  floorGroup.add(floorBack);
};

const createRoomMark = (floorGroup) => {
  let roomList = [],
    apList = [];
  const arr = JSON.parse(JSON.stringify(data.sysLocationList));
  //获取楼层下信息(信息点、房间、配线间)
  arr.forEach((item) => {
    apList = apList.concat(item.deviceApList);
    delete item.deviceApList;
    roomList.push(item);
  });
  let offsetX = imgInfo.width / 2,
    offsetZ = imgInfo.height / 2;
  //创建节点
  console.log(arr, apList);

  apList.forEach((item) => {
    const map = new THREE.TextureLoader().load(baseUrl + item.deviceModelAp.imageUrl);
    const material = new THREE.SpriteMaterial({ map: map });
    const sprite = new THREE.Sprite(material);

    sprite.position.set(item.locationX ? item.locationX - offsetX : 0, 100, item.locationY ? item.locationY - offsetZ : 0);
    floorGroup.add(sprite);
    sprite.scale.set(100, 100, 100);
  });

  roomList.forEach((item) => {
    const map = new THREE.TextureLoader().load(item.locationType == 6 ? "/img/iim/room.png" : "/img/iim/frame.png");
    const material = new THREE.SpriteMaterial({ map: map });
    const sprite = new THREE.Sprite(material);

    sprite.position.set(item.locationX ? item.locationX - offsetX : 0, 100, item.locationY ? item.locationY - offsetZ : 0);
    floorGroup.add(sprite);
    sprite.scale.set(100, 100, 100);
  });
};
